#include "myinet.h"
#include "tools.h"
#include <poll.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <sys/socket.h>

// 同时提供UDP,TCP服务的datetime服务

static char*
getTimeString() {
    time_t now;
    time(&now);
    return ctime(&now);
}

int
main(int argc, char** argv) {
    if (argc != 2) {
        warn("Usage: %s [port]", argv[0]);
        exit(-1);
    }

    int portNumber = atoi(argv[1]);

    char buffer[512];

    struct pollfd fds[2];

    // tcp
    fds[0].fd = get_server_socket(portNumber, SOCK_STREAM, 10);
    fds[0].events = POLLIN;

    // udp
    fds[1].fd = get_server_socket(portNumber, SOCK_DGRAM, 10);
    fds[1].events = POLLIN;

    // infinite wait
    // till received requests
    while(poll(fds, 2, -1) > 0) {
        struct sockaddr_in addr;
        int len;
        // tcp
        if (fds[0].revents & POLLIN) {
            fds[0].revents &= ~POLLIN;
            printf("tcp\n");
            int newfd = accept(fds[0].fd, (struct sockaddr*)&addr, &len);
            info("connected");
            char* timestr = getTimeString();
            read(newfd, buffer, sizeof(buffer));
            int sent = write(newfd, timestr, strlen(timestr));
            close(newfd);
            info("%d bytes sent to %s:%d", sent,
                    inet_ntoa(addr.sin_addr),
                    ntohs(addr.sin_port));
        }

        if (fds[1].revents & POLLIN) {
            //
            printf("udp\n");
            recvfrom(fds[1].fd, buffer, sizeof(buffer), 0, &addr, &len);
            char* timestr = getTimeString();
            int sent = sendto(fds[1].fd, timestr, strlen(timestr), 0,
                    (struct sockaddr*)&addr, len);
            info("%d bytes sent to %s:%d", sent,
                    inet_ntoa(addr.sin_addr),
                    ntohs(addr.sin_port));
        }
    }

    printf("bye\n");
    return 0;
}
